import {invoke} from '@tauri-apps/api/core';
import {ToM} from "@/schemas/base.ts";
import {mToS, sToM} from '@/common/converts.ts';
import {
    InvokeResponse, InvokeResult,
    ListQuery,
    Payload,
    PayloadType, ListResult, EffectOne, DuckQuery
} from "@/schemas/invoke.ts";
import {Toast} from "@douyinfe/semi-ui";


export const invokeOperationOne = async <T extends { [k: string]: any }>(
    path: string, type: PayloadType, d: T, noTip?: boolean
): Promise<InvokeResponse<EffectOne<T>>> => {
    const data = sToM(d)
    const payload: Payload<ToM<T>> = {type, data}
    try {
        const result: InvokeResult<EffectOne<T>> = await invoke('router', {path, payload});
        if (!noTip) Toast.success("操作成功!")
        return {ok: true, ...result};
    } catch (err) {
        if (!noTip) Toast.error(`操作失败!${err}`)
        console.log(`Invoke error, path: ${path}, type: ${type}, data: ${d}, err: ${err}`)
        return {ok: false};
    }
}

export const invokeAllQuery = async <R>(
    path: string, type: PayloadType, d: any
): Promise<InvokeResponse<Array<R>>> => {
    const data = sToM(d)
    const payload: Payload<ToM<any>> = {type, data}
    try {
        const result: InvokeResult<Array<R>> = await invoke('router', {path, payload});
        result.data = mToS(result.data);
        return {ok: true, ...result};
    } catch (err) {
        Toast.error(`数据查询失败! ${err}`);
        console.log(`Invoke error, path: ${path}, type: ${type}, data: ${d}, err: ${err}`)
        return {ok: false};
    }
}


export const invokeListQuery = async <R>(
    path: string, type: PayloadType, d: ListQuery
): Promise<InvokeResponse<ListResult<R>>> => {
    const data = sToM(d)
    const payload: Payload<ToM<ListQuery>> = {type, data}
    try {
        const result: InvokeResult<ListResult<R>> = await invoke('router', {path, payload});
        result.data.result = result.data?.result?.map(i => mToS(i)) || [];
        return {ok: true, ...result};
    } catch (err) {
        Toast.error(`数据查询失败! ${err}`);
        console.log(`Invoke error, path: ${path}, type: ${type}, data: ${d}, err: ${err}`)
        return {ok: false};
    }
}


export const invokeDuckQuery = async <R>(
    path: string, type: PayloadType, data: DuckQuery
):Promise<InvokeResponse<ListResult<R>>> => {
    const payload: Payload<ToM<DuckQuery>> = {type, data}
    try {
        const result: InvokeResult<ListResult<R>> = await invoke('router', {path, payload});
        return {ok: true, ...result};
    } catch (err) {
        Toast.error(`数据查询失败! ${err}`);
        console.log(`Invoke error, path: ${path}, type: ${type}, data: ${data}, err: ${err}`)
        return {ok: false};
    }
}